#include "StdAfx.h"
#include "SocketList.h"

CSocketList::CSocketList(void)
{
}

CSocketList::~CSocketList(void)
{
	for (int i = 0;i<_myUserList.size();i++)
		if (_myUserList[i]!=NULL)
			delete(_myUserList[i]);
}
void CSocketList::Push(SOCKET iSocket)
{
	_mySocketList.push_back(iSocket);
	_myUserList.resize(_mySocketList.size());
}
int CSocketList::Size()
{
	return _mySocketList.size();
}
SOCKET CSocketList::GetByIndex(int iIndex)
{
	if (iIndex < _mySocketList.size())
		return _mySocketList[iIndex];
	else
		return NULL;
}
int CSocketList::FindBySocket(SOCKET iSoc)
{
	for (int i = 0;i<_mySocketList.size();i++)
		if (_mySocketList[i] == iSoc)
			return i;
	return -1;
}
int CSocketList::FindByUserName(char* iUserName)
{
	for (int i = 0;i<_myUserList.size();i++)
	{		
		if (_myUserList[i]==NULL)
		{
			continue;
		}
		if (strcmp(_myUserList[i],iUserName) == 0)
			return i;
	}
	return -1;
}
bool CSocketList::SetUserName(int iIndex,char* iUserName)
{
	if (iIndex < 0 || iIndex>=_mySocketList.size())
		return false;
	if (_myUserList[iIndex] == NULL)
		_myUserList[iIndex] = new char[20];
	strcpy(_myUserList[iIndex],iUserName);
	return true;
}


bool CSocketList::CheckUser( char* username,char* pass ,SOCKET soc)
{
	bool result=CServerSideUserList::getInstance()->CheckUser(username,pass);
	int isOnline=FindByUserName(username);
	if (result && isOnline==-1)
	{
		int iTempSocketArrayIndex = FindBySocket(soc);
		SetUserName(iTempSocketArrayIndex,username);
		return true;
	}
	return false;
}

void CSocketList::UserLogout( char* username )
{
	int index=FindByUserName(username);
	_mySocketList.erase(_mySocketList.begin()+index);
	_myUserList.erase(_myUserList.begin()+index);
}
